using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CapstoneProject.Models;

namespace CapstoneProject.Activities
{
    [Activity(Label = "Add Account")]
    public class NameAccountActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.NameAccount);

            Button addAccountButton = FindViewById<Button>(Resource.Id.AddAccountButton);
            addAccountButton.Click += AddAccount;
        }

        private void AddAccount(object sender, EventArgs e)
        {
            EditText accountName = FindViewById<EditText>(Resource.Id.AccountNameField);
            Account existingAccount = ((CapstoneApplication)Application).AccountRepository.GetAllAccounts().FirstOrDefault(a => a.AccountName == accountName.Text);

            if (existingAccount == null)
            {
                ((CapstoneApplication)Application).AccountRepository.AddAccount(Intent.GetStringExtra("Username"), Intent.GetStringExtra("Password"), Intent.GetStringExtra("FiUrl"), Intent.GetStringExtra("FiOrg"), Intent.GetStringExtra("Fid"), Intent.GetStringExtra("AccountNumber"), Intent.GetStringExtra("Routing"), accountName.Text, Intent.GetIntExtra("UserId", 0));

                Finish();
                User user = ((CapstoneApplication)Application).UserRepository.GetAllUsers().FirstOrDefault(u => u.UserId == Intent.GetIntExtra("UserId", 0));
                Intent i = new Intent();
                i.SetClass(this, typeof(ProfileActivity));
                i.AddFlags(ActivityFlags.NewTask);
                i.PutExtra("User", user.Username);
                StartActivity(i);
            }
            else
            {
                TextView error = FindViewById<TextView>(Resource.Id.NameAccountError);
                error.Text = "An account with that name already exists.";
            }
        }
    }
}